package com.jiamu.es;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ProductService {

    private final ProductRepository productRepository;
    private final ElasticsearchClient elasticsearchClient;

    @Autowired
    public ProductService(ProductRepository productRepository, ElasticsearchClient elasticsearchClient) {
        this.productRepository = productRepository;
        this.elasticsearchClient = elasticsearchClient;
    }

    // Create or Update
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    // Read by ID
    public Optional<Product> getProductById(String id) {
        return productRepository.findById(id);
    }

    // Delete by ID
    public void deleteProduct(String id) {
        productRepository.deleteById(id);
    }

    // Search by Category using ElasticsearchClient
    public List<Product> searchByCategory(String category) throws IOException {
        SearchResponse<Product> response = elasticsearchClient.search(s -> s
                        .index("products")
                        .query(q -> q
                                .match(m -> m
                                        .field("category")
                                        .query(category)
                                )
                        ),
                Product.class);

        return response.hits().hits().stream()
                .map(hit -> hit.source())
                .collect(Collectors.toList());
    }
}
